package problems.practice;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 56. 合并区间
 * https://leetcode.cn/problems/merge-intervals/
 *
 * @author habitplus
 * @since 2022/8/2 11:37
 */
public class T56_1 {

    public int[][] merge(int[][] intervals) {
        if (intervals == null || intervals.length < 2) return intervals;

        int n = intervals.length;

        // 排序
        Arrays.sort(intervals, (o1, o2) -> o1[0] == o2[0] ? o1[1] - o2[1] : o1[0] - o2[0]);

        int s = intervals[0][0];
        int e = intervals[0][1];

        List<int[]> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (e < intervals[i][0]) {
                // 没有交集
                list.add(new int[]{s, e});
                s = intervals[i][0];
                e = intervals[i][1];
            } else {
                e = Math.max(intervals[i][1], e);
            }
        }

        list.add(new int[]{s, e});

//        int[][] ans = new int[list.size()][];
//        s = 0;
//        for (int[] a : list) {
//            ans[s++] = a;
//        }
//        return ans;
        return list.toArray(new int[0][]);
    }

}
